package org.linlinjava.litemall.admin.web;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.linlinjava.litemall.admin.annotation.RequiresPermissionsDesc;
import org.linlinjava.litemall.core.storage.StorageService;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.core.validator.Order;
import org.linlinjava.litemall.core.validator.Sort;
import org.linlinjava.litemall.db.domain.LitemallStorage;
import org.linlinjava.litemall.db.service.LitemallStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.net.URI;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin/storage")
@Validated
public class AdminStorageController {
    private final Log logger = LogFactory.getLog(AdminStorageController.class);

    @Autowired
    private StorageService storageService;
    @Autowired
    private LitemallStorageService litemallStorageService;

    @RequiresPermissions("admin:storage:list")
    @RequiresPermissionsDesc(menu = {"系统管理", "对象存储"}, button = "查询")
    @GetMapping("/list")
    public Object list(String key, String name,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer limit,
                       @Sort @RequestParam(defaultValue = "add_time") String sort,
                       @Order @RequestParam(defaultValue = "desc") String order) {
        List<LitemallStorage> storageList = litemallStorageService.querySelective(key, name, page, limit, sort, order);
        return ResponseUtil.okList(storageList);
    }

    @RequiresPermissions("admin:storage:create")
    @RequiresPermissionsDesc(menu = {"系统管理", "对象存储"}, button = "上传")
    @PostMapping("/create")
    public Object create(@RequestParam("file") MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        LitemallStorage litemallStorage = storageService.store(file.getInputStream(), file.getSize(),
                file.getContentType(), originalFilename);
        
        // 构建返回数据
        Map<String, Object> data = new HashMap<>();
        data.put("id", litemallStorage.getId());
        data.put("key", litemallStorage.getKey());
        data.put("name", litemallStorage.getName());
        data.put("url", litemallStorage.getUrl());
        data.put("size", litemallStorage.getSize());
        data.put("type", litemallStorage.getType());
        data.put("originalName", originalFilename);
        
        // 如果是PDF文件，提取页数
        if ("application/pdf".equals(file.getContentType())) {
            try {
                PDDocument document = PDDocument.load(file.getInputStream());
                int pageCount = document.getNumberOfPages();
                data.put("pdfTotalPages", pageCount);
                document.close();
                logger.info("PDF文件页数提取成功: " + pageCount + " 页");
            } catch (Exception e) {
                logger.error("PDF页数提取失败: " + e.getMessage(), e);
                data.put("pdfTotalPages", 1); // 默认值
            }
        }
        
        return ResponseUtil.ok(data);
    }

    @RequiresPermissions("admin:storage:read")
    @RequiresPermissionsDesc(menu = {"系统管理", "对象存储"}, button = "详情")
    @PostMapping("/read")
    public Object read(@NotNull Integer id) {
        LitemallStorage storageInfo = litemallStorageService.findById(id);
        if (storageInfo == null) {
            return ResponseUtil.badArgumentValue();
        }
        return ResponseUtil.ok(storageInfo);
    }

    @RequiresPermissions("admin:storage:update")
    @RequiresPermissionsDesc(menu = {"系统管理", "对象存储"}, button = "编辑")
    @PostMapping("/update")
    public Object update(@RequestBody LitemallStorage litemallStorage) {
        if (litemallStorageService.update(litemallStorage) == 0) {
            return ResponseUtil.updatedDataFailed();
        }
        return ResponseUtil.ok(litemallStorage);
    }

    @RequiresPermissions("admin:storage:delete")
    @RequiresPermissionsDesc(menu = {"系统管理", "对象存储"}, button = "删除")
    @PostMapping("/delete")
    public Object delete(@RequestBody LitemallStorage litemallStorage) {
        String key = litemallStorage.getKey();
        if (StringUtils.isEmpty(key)) {
            return ResponseUtil.badArgument();
        }
        litemallStorageService.deleteByKey(key);
        storageService.delete(key);
        return ResponseUtil.ok();
    }

    /**
     * 访问存储对象
     *
     * @param key 存储对象key
     * @return
     */
    @RequiresPermissions("admin:storage:fetch")
    @RequiresPermissionsDesc(menu = {"系统管理", "对象存储"}, button = "访问")
    @GetMapping("/fetch/{key:.+}")
    public ResponseEntity<Resource> fetch(@PathVariable String key) {
        LitemallStorage litemallStorage = litemallStorageService.findByKey(key);
        if (litemallStorage == null || key == null) {
            return ResponseEntity.notFound().build();
        }
        if (key.contains("../")) {
            return ResponseEntity.badRequest().build();
        }
        String type = litemallStorage.getType();
        MediaType mediaType = MediaType.parseMediaType(type);

        Resource file = storageService.loadAsResource(key);
        if (file == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok().contentType(mediaType).body(file);
    }

    /**
     * 公开访问PDF文件（用于预览，无需权限）
     *
     * @param key 存储对象key
     * @return
     */
    @GetMapping("/pdf/test")
    public ResponseEntity<String> testPdf() {
        logger.info("PDF test endpoint accessed");
        return ResponseEntity.ok("PDF test endpoint is working");
    }
    
    @GetMapping("/pdf/**")
    public ResponseEntity<Resource> fetchPdf(HttpServletRequest request) {
        String key = request.getRequestURI().substring("/admin/storage/pdf/".length());
        logger.info("=== PDF ACCESS REQUEST START ===");
        logger.info("PDF access request for key: " + key);
        logger.info("Key length: " + (key != null ? key.length() : "null"));
        logger.info("Key contains slash: " + (key != null && key.contains("/")));
        
        // 只允许访问PDF文件
        if (!key.toLowerCase().endsWith(".pdf")) {
            logger.warn("Invalid PDF file extension for key: " + key);
            return ResponseEntity.badRequest().build();
        }
        
        LitemallStorage litemallStorage = litemallStorageService.findByKey(key);
        if (litemallStorage == null || key == null) {
            logger.warn("PDF file not found in database for key: " + key);
            return ResponseEntity.notFound().build();
        }
        logger.info("Found PDF file in database: " + litemallStorage.getUrl());
        if (key.contains("../")) {
            return ResponseEntity.badRequest().build();
        }
        
        // 确保是PDF类型
        String type = litemallStorage.getType();
        if (!"application/pdf".equals(type)) {
            return ResponseEntity.badRequest().build();
        }
        
        // 如果URL是外部地址，直接重定向
        String url = litemallStorage.getUrl();
        if (url != null && (url.startsWith("http://") || url.startsWith("https://"))) {
            return ResponseEntity.status(HttpStatus.FOUND)
                    .location(URI.create(url))
                    .build();
        }
        
        // 否则尝试从本地存储加载
        MediaType mediaType = MediaType.parseMediaType(type);
        Resource file = storageService.loadAsResource(key);
        if (file == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok().contentType(mediaType).body(file);
    }
}
